import { defineStore } from 'pinia';
import { ref } from 'vue';
import { commonRoutes, convertRoutes } from '@/router/routes';
import router from '@/router';

const useStore = defineStore(
  'route-store',
  () => {
    const staticRoutes = ref([]);
    const dynamicRoutes = ref([]);
    const isInitStaticRoute = ref(false);
    const isInitDynamicRoute = ref(false);
    const removeFuns = [];

    function resetStore() {
      const store = useStore();
      store.$reset();
      store.$clearCache();
      resetRoutes();
    }

    function resetRoutes() {
      removeFuns.forEach((fun) => fun());
      removeFuns.length = 0;
    }

    function setupRoutes() {
      resetRoutes();
      const routes = staticRoutes.value;
      routes.forEach((route) => {
        const func = router.addRoute(route);
        removeFuns.push(func);
      });

      // 动态路由
      convertRoutes(dynamicRoutes.value).forEach((route) => {
        const func = router.addRoute('layout', route);
        removeFuns.push(func);
      });
    }

    async function initStaticRoutes() {
      if (isInitStaticRoute.value) {
        return;
      }
      addStaticRoutes(commonRoutes);
      setupRoutes();
      isInitStaticRoute.value = true;
    }

    function addStaticRoutes(routes = []) {
      const routesMap = new Map();
      routes.forEach((route) => {
        routesMap.set(route.name, route);
      });
      staticRoutes.value = Array.from(routesMap.values());
    }

    function initDynamicRoute() {
      if (isInitDynamicRoute.value) {
        return;
      }
      setupRoutes();
      isInitDynamicRoute.value = true;
    }

    function addDynamicRoutes(routes) {
      const store = useStore();
      const routesMap = new Map();
      routes.forEach((route) => {
        routesMap.set(route.name, route);
      });
      const data = Array.from(routesMap.values());
      store.$patch({ dynamicRoutes: data });
    }

    function checkedRouteExist(path) {
      const routes = router.getRoutes();
      return routes.findIndex((v) => v.path === path) !== -1;
    }

    return {
      resetStore,
      staticRoutes,
      isInitStaticRoute,
      initStaticRoutes,
      dynamicRoutes,
      isInitDynamicRoute,
      addDynamicRoutes,
      initDynamicRoute,
      checkedRouteExist
    };
  },
  {
    resetEnable: true,
    storage: {
      enable: true, // 开启存储功能
      key: 'route', // 缓存key
      picks: ['dynamicRoutes'], // 缓存字段
      aloneFields: true // 存储单独字段
    }
  }
);

export default useStore;
